class Solution:
    def minSumOfLengths(self, arr: list, target: int) -> int:
        prefix = [2**31 for _ in range(len(arr))]
        suffix = [2**31 for _ in range(len(arr))]
        arrSum = 0
        sumDict = {}
        for i in range(len(arr) - 1):
            arrSum += arr[i]
            sumDict[arrSum] = i
            if i == 0:
                prefix[i] = 1 if arr[i] == target else prefix[i]
            elif arr[i] == target:
                prefix[i] = 1
            elif arrSum == target:
                prefix[i] = min(prefix[i - 1], i + 1)
            elif arrSum > target:
                diff = arrSum - target
                if diff in sumDict:
                    prefix[i] = min(prefix[i - 1], i - sumDict[diff])
                else:
                    prefix[i] = prefix[i - 1]
        arrSum = 0
        sumDict = {}
        for i in range(len(arr) - 1, 0, -1):
            arrSum += arr[i]
            sumDict[arrSum] = i
            if i == len(arr) - 1:
                suffix[i] = 1 if arr[i] == target else suffix[i]
            elif arr[i] == target:
                suffix[i] = 1
            elif arrSum == target:
                suffix[i] = min(suffix[i + 1], len(arr) - i)
            elif arrSum > target:
                diff = arrSum - target
                if diff in sumDict:
                    suffix[i] = min(suffix[i + 1], sumDict[diff] - i)
                else:
                    suffix[i] = suffix[i + 1]

        ans = 2**31
        for i in range(len(arr) - 1):
            p = prefix[i]
            s = suffix[i + 1]
            ans = min(ans, p + s)
        return -1 if ans == 2**31 else ans
